package com.ma4567.remotecontroller.FileRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.RemoteControllerApplication;
import com.ma4567.remotecontroller.ffmpegManager.ffmpegController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

class FileUploadRespone extends com.ma4567.remotecontroller.util.CustomRespone{

    public FileUploadRespone(int status) {
        super(status);//0 正常 1 cookie 错误 2 上传路径错误 3 文件上传失败 4 没有权限

    }
}

@CrossOrigin
@RestController
public class FIleUploadRequest {
    @RequestMapping(value = "/api/uploadFile", method = RequestMethod.GET)
    public String uploadFile(@RequestParam("cookie") String Cookie,
                             @RequestParam("path") String path,
                             @RequestParam("file") MultipartFile file){
        ffmpegController.StopStream();
        System.out.println("Cookie: " + Cookie + " upload file: " + path + file.getOriginalFilename());
        if(!RemoteControllerApplication.userManager.JudgeCookie(Cookie)){//鉴权
            return JSONObject.toJSONString(new FileUploadRespone(1), SerializerFeature.PrettyFormat);
        }

        if(!RemoteControllerApplication.userManager.GetUserSingleItemPermission(Cookie, "UploadFile")){
            return JSONObject.toJSONString(new FileDownloadRespone(4), SerializerFeature.PrettyFormat);
        }

        File pathFile = new File(path);
        if(pathFile.exists()){
            if(pathFile.isDirectory()){
                if(file.isEmpty()){
                    return JSONObject.toJSONString(new FileUploadRespone(3), SerializerFeature.PrettyFormat);
                }
                else{
                    try {
                        byte[] bytes = file.getBytes();
                        File uploadedFile = new File(path + file.getOriginalFilename());
                        file.transferTo(uploadedFile);
                        return JSONObject.toJSONString(new FileUploadRespone(0), SerializerFeature.PrettyFormat);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return JSONObject.toJSONString(new FileUploadRespone(3), SerializerFeature.PrettyFormat);
                    }
                }
            }
            else {
                return JSONObject.toJSONString(new FileUploadRespone(2), SerializerFeature.PrettyFormat);
            }
        }
        else {
            return JSONObject.toJSONString(new FileUploadRespone(2), SerializerFeature.PrettyFormat);
        }
    }

}
